﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.d
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using EffiProz.Core.Persist;
using EffiProz.Core.Lib;

namespace EffiProz.Core
{
    class TransactionManager2PL : TransactionManager
    {
        Database database;

        //
        ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

        // functional unit - sessions involved in live transactions
        /** live transactions keeping committed transactions from being merged */
        public long globalChangeTimestamp;

        // functional unit - cached table transactions
        //
        //
        HashMap tableWriteLocks = new HashMap();
        MultiValueHashMap tableReadLocks = new MultiValueHashMap();

        public TransactionManager2PL(Database db)
        {
            database = db;
        }

        public long getGlobalChangeTimestamp()
        {
            return Interlocked.Read(ref globalChangeTimestamp);
        }

        public bool isMVRows()
        {
            return false;
        }

        public int getTransactionControl()
        {
            return Database.LOCKS;
        }

        public void setTransactionControl(Session session, int mode)
        {

            _lock.EnterWriteLock();

            try
            {
                switch (mode)
                {

                    case Database.MVCC:
                        {
                            TransactionManagerMVCC manager =
                                new TransactionManagerMVCC(database);
                            long tmp = Interlocked.Read(
                               ref globalChangeTimestamp);
                            Interlocked.Exchange(ref manager.globalChangeTimestamp, tmp);
                            manager.liveTransactionTimestamps.addLast(
                                session.transactionTimestamp);

                            database.txManager = manager;

                            break;
                        }
                    case Database.MVLOCKS:
                        {
                            TransactionManagerMV2PL manager =
                                new TransactionManagerMV2PL(database);

                            long tmp = Interlocked.Read(
                                ref globalChangeTimestamp);

                            Interlocked.Exchange(ref manager.globalChangeTimestamp, tmp);
                            manager.liveTransactionTimestamps.addLast(
                                session.transactionTimestamp);

                            database.txManager = manager;

                            break;
                        }
                    case Database.LOCKS:
                        break;
                }

                return;
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        public void completeActions(Session session)
        {

            Object[] list = session.rowActionList.getArray();
            int limit = session.rowActionList.size();

            for (int i = session.actionIndex; i < limit; i++)
            {
                RowAction rowact = (RowAction)list[i];

                rowact.complete(session, null);
            }
        }

        public bool prepareCommitActions(Session session)
        {

            session.actionTimestamp = nextChangeTimestamp();

            return true;
        }

        public bool commitTransaction(Session session)
        {

            if (session.abortTransaction)
            {
                return false;
            }

            int limit = session.rowActionList.size();
            Object[] list = limit == 0 ? new object[0]
                                        : session.rowActionList.getArray();

            try
            {
                _lock.EnterWriteLock();
                endTransaction(session);

                if (limit == 0)
                {
                    endTransactionTPL(session);

                    try
                    {
                        session.logSequences();
                    }
                    catch (CoreException) { }

                    return true;
                }

                // new actionTimestamp used for commitTimestamp
                // already set in prepareCommitActions();
                session.actionTimestamp = nextChangeTimestamp();

                for (int i = 0; i < limit; i++)
                {
                    RowAction action = (RowAction)list[i];

                    action.commit(session);
                }

                for (int i = 0; i < limit; i++)
                {
                    RowAction action = (RowAction)list[i];

                    if (action.type == RowActionBase.ACTION_NONE)
                    {
                        continue;
                    }

                    int type = action.getCommitType(session.actionTimestamp);
                    PersistentStore store =
                        session.sessionData.getRowStore(action.table);
                    Row row = action.memoryRow;

                    if (row == null)
                    {
                        row = (Row)store.get(action.getPos(), false);
                    }

                    if (action.table.hasLobColumn)
                    {
                        switch (type)
                        {

                            case RowActionBase.ACTION_INSERT:
                                action.table.addLobUsageCount(session,
                                                              row.getData());
                                break;

                       
                        }
                    }

                    if (action.table.tableType == TableBase.TEXT_TABLE)
                    {
                        switch (type)
                        {

                            case RowActionBase.ACTION_DELETE:
                                store.removePersistence(action.getPos());
                                break;

                            case RowActionBase.ACTION_INSERT:
                                store.commitPersistence(row);
                                break;

                        
                        }

                        action.setAsNoOp(row);
                    }
                    else
                    {
                        Object[] data = row.getData();

                        try
                        {
                            switch (type)
                            {

                                case RowActionBase.ACTION_DELETE:
                                    database.logger.writeDeleteStatement(
                                        session, action.table, data);
                                    store.remove(action.getPos());
                                    break;

                                case RowActionBase.ACTION_INSERT:
                                    database.logger.writeInsertStatement(
                                        session, action.table, data);
                                    break;

                                case RowActionBase.ACTION_NONE:

                                    // ????
                                    store.remove(action.getPos());
                                    break;
                            }

                            action.setAsNoOp(row);
                        }
                        catch (CoreException e)
                        {
                            database.logger.logWarningEvent("logging problem", e);
                        }
                    }
                }

                try
                {
                    session.logSequences();
                    database.logger.writeCommitStatement(session);
                }
                catch (CoreException ) { }

                endTransactionTPL(session);

                return true;
            }
            finally
            {
                _lock.ExitWriteLock();
                session.tempSet.clear();
            }
        }

        public void rollback(Session session)
        {

            session.abortTransaction = false;
            session.actionTimestamp = nextChangeTimestamp();

            rollbackPartial(session, 0, session.transactionTimestamp);
            endTransaction(session);

            try
            {
                _lock.EnterWriteLock();
                endTransactionTPL(session);
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        public void rollbackSavepoint(Session session, int index)
        {

            long timestamp = session.sessionContext.savepointTimestamps.get(index);
            int oi = Convert.ToInt32(session.sessionContext.savepoints.get(index));
            int start = oi;

            while (session.sessionContext.savepoints.size() > index + 1)
            {
                session.sessionContext.savepoints.remove(
                    session.sessionContext.savepoints.size() - 1);
                session.sessionContext.savepointTimestamps.removeLast();
            }

            rollbackPartial(session, start, timestamp);
        }

        public void rollbackAction(Session session)
        {
            rollbackPartial(session, session.actionIndex, session.actionTimestamp);
        }

        /**
         * rollback the row actions from start index in list and
         * the given timestamp
         */
        void rollbackPartial(Session session, int start, long timestamp)
        {

            Object[] list = session.rowActionList.getArray();
            int limit = session.rowActionList.size();

            if (start == limit)
            {
                return;
            }

            for (int i = limit - 1; i >= start; i--)
            {
                RowAction action = (RowAction)list[i];

                if (action == null || action.type == RowActionBase.ACTION_NONE
                        || action.type == RowActionBase.ACTION_DELETE_FINAL)
                {
                    continue;
                }

                Row row = action.memoryRow;
                PersistentStore store =
                    session.sessionData.getRowStore(action.table);

                if (row == null)
                {
                    row = (Row)store.get(action.getPos(), false);
                }

                if (row == null)
                {
                    continue;
                }

                action.rollback(session, timestamp);

                int type = action.getCommitType(session.actionTimestamp);

                action.mergeRollback(row);

                if (type == RowActionBase.ACTION_DELETE)
                {
                    store.indexRow(session, row);
                }
                else if (type == RowActionBase.ACTION_INSERT)
                {
                    store.delete(row);
                    store.remove(action.getPos());
                }
            }

            session.rowActionList.setSize(start);
        }

        public RowAction addDeleteAction(Session session, Table table, Row row)
        {

            RowAction action;

            lock (row)
            {
                action = RowAction.addAction(session, RowActionBase.ACTION_DELETE,
                                             table, row);
            }

            session.rowActionList.add(action);

            PersistentStore store = session.sessionData.getRowStore(table);

            store.delete(row);

            return action;
        }

        public void addInsertAction(Session session, Table table, Row row)
        {

            RowAction action = row.rowAction;

            if (action == null)
            {
                System.Diagnostics.Debug.WriteLine("null insert action " + session + " "
                                   + session.actionTimestamp);
            }

            session.rowActionList.add(action);
        }

        // functional unit - row comparison

        /**
         * Used for inserting rows into unique indexes
         */

        /** @todo test skips some equal rows because it relies on getPos() */
        int compareRowForInsert(Row newRow, Row existingRow)
        {

            // only allow new inserts over rows deleted by the same session
            if (newRow.rowAction != null
                    && !canRead(newRow.rowAction.session, existingRow))
            {
                return newRow.getPos() - existingRow.getPos();
            }

            return 0;
        }

        // functional unit - accessibility of rows
        public bool canRead(Session session, Row row)
        {

            RowAction action = row.rowAction;

            if (action == null)
            {
                return true;
            }

            return action.canRead(session);
        }

        public bool isDeleted(Session session, Row row)
        {

            RowAction action = row.rowAction;

            if (action == null)
            {
                return false;
            }

            return !action.canRead(session);
        }

        public bool canRead(Session session, int id)
        {
            return true;
        }

        /**
         * add transaction info to a row just loaded from the cache. called only
         * for CACHED tables
         */
        public void setTransactionInfo(CachedObject _object) { }

        /**
         * gets the next timestamp for an action
         */
        long nextChangeTimestamp()
        {
            return Interlocked.Increment(ref globalChangeTimestamp);
        }

        public void beginTransaction(Session session)
        {

            session.actionTimestamp = nextChangeTimestamp();
            session.transactionTimestamp = session.actionTimestamp;
            session.isTransaction = true;
        }

        /**
         * add session to the end of queue when a transaction starts
         * (depending on isolation mode)
         */
        public void beginAction(Session session, Statement cs)
        {

            session.actionTimestamp = nextChangeTimestamp();

            if (!session.isTransaction)
            {
                session.transactionTimestamp = session.actionTimestamp;
                session.isTransaction = true;
            }

            if (session.hasLocks())
            {
                return;
            }

            try
            {
                _lock.EnterWriteLock();

                bool canProceed = beginActionTPL(session, cs);

                if (!canProceed)
                {
                    session.abortTransaction = true;
                }
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        void endTransactionTPL(Session session)
        {

            int unlockedCount = 0;

            unlockTablesTPL(session);

            int waitingCount = session.waitingSessions.size();

            if (waitingCount == 0)
            {
                return;
            }

            for (int i = 0; i < waitingCount; i++)
            {
                Session current = (Session)session.waitingSessions.get(i);

                current.tempUnlocked = false;

                long count = current.latch.getCount();

                if (count == 1)
                {
                    bool canProceed = setWaitedSessionsTPL(current,
                        current.currentStatement);

                    if (!canProceed)
                    {
                        current.abortTransaction = true;
                    }

                    if (current.tempSet.isEmpty())
                    {
                        lockTablesTPL(current, current.currentStatement);

                        current.tempUnlocked = true;

                        unlockedCount++;
                    }
                }
            }

            for (int i = 0; i < waitingCount; i++)
            {
                Session current = (Session)session.waitingSessions.get(i);

                if (!current.tempUnlocked)
                {

                    // this can introduce additional waits for the sessions
                    bool canProceed = setWaitedSessionsTPL(current,
                        current.currentStatement);

                    if (!canProceed)
                    {
                        current.abortTransaction = true;
                    }
                }
            }

            for (int i = 0; i < waitingCount; i++)
            {
                Session current = (Session)session.waitingSessions.get(i);

                if (current.tempSet.isEmpty())
                {
                    bool haslocks = hasLocks(current, current.currentStatement);

                    if (!haslocks)
                    {
                        System.Diagnostics.Debug.WriteLine("trouble");
                    }
                }

                setWaitingSessionTPL(current);
            }

            session.tempSet.clear();
            session.waitingSessions.clear();
        }

        public bool beginActionTPL(Session session, Statement cs)
        {

            bool canProceed = setWaitedSessionsTPL(session, cs);

            if (canProceed)
            {
                if (session.tempSet.isEmpty())
                {
                    lockTablesTPL(session, cs);

                    // we dont set other sessions that would now be waiting for this one too
                }
                else
                {
                    setWaitingSessionTPL(session);
                }

                return true;
            }

            return false;
        }

        public bool setWaitedSessionsTPL(Session session, Statement cs)
        {

            session.tempSet.clear();

            if (cs == null || session.abortTransaction)
            {
                return true;
            }

            QNameManager.QName[] nameList = cs.getTableNamesForWrite();

            for (int i = 0; i < nameList.Length; i++)
            {
                QNameManager.QName name = nameList[i];

                if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                {
                    continue;
                }

                Session holder = (Session)tableWriteLocks.get(name);

                if (holder != null && holder != session)
                {
                    session.tempSet.add(holder);
                }

                Iterator it = tableReadLocks.get(name);

                while (it.hasNext())
                {
                    holder = (Session)it.next();

                    if (holder != session)
                    {
                        session.tempSet.add(holder);
                    }
                }
            }

            nameList = cs.getTableNamesForRead();

            for (int i = 0; i < nameList.Length; i++)
            {
                QNameManager.QName name = nameList[i];

                if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                {
                    continue;
                }

                Session holder = (Session)tableWriteLocks.get(name);

                if (holder != null && holder != session)
                {
                    session.tempSet.add(holder);
                }
            }

            for (int i = 0; i < session.waitingSessions.size(); i++)
            {
                Session current = (Session)session.waitingSessions.get(i);

                if (session.tempSet.contains(current))
                {
                    session.tempSet.clear();

                    return false;
                }
            }

            return true;
        }

        public void setWaitingSessionTPL(Session session)
        {

            int count = session.tempSet.size();

            for (int i = 0; i < count; i++)
            {
                Session current = (Session)session.tempSet.get(i);

                current.waitingSessions.add(session);
            }

            session.tempSet.clear();
            session.latch.setCount(count);
        }

        public void lockTablesTPL(Session session, Statement cs)
        {

            if (cs == null || session.abortTransaction)
            {
                return;
            }

            QNameManager.QName[] nameList = cs.getTableNamesForWrite();

            for (int i = 0; i < nameList.Length; i++)
            {
                QNameManager.QName name = nameList[i];

                if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                {
                    continue;
                }

                tableWriteLocks.put(name, session);
            }

            nameList = cs.getTableNamesForRead();

            for (int i = 0; i < nameList.Length; i++)
            {
                QNameManager.QName name = nameList[i];

                if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                {
                    continue;
                }

                tableReadLocks.put(name, session);
            }
        }

        public void unlockTablesTPL(Session session)
        {

            Iterator it = tableWriteLocks.values().iterator();

            while (it.hasNext())
            {
                Session s = (Session)it.next();

                if (s == session)
                {
                    it.setValue(null);
                }
            }

            it = tableReadLocks.values().iterator();

            while (it.hasNext())
            {
                Session s = (Session)it.next();

                if (s == session)
                {
                    it.remove();
                }
            }
        }

        /**
         * remove session from queue when a transaction ends
         * and expire any committed transactions
         * that are no longer required. remove transactions ended before the first
         * timestamp in liveTransactionsSession queue
         */
        public void endTransaction(Session session)
        {
            session.isTransaction = false;
        }

        public bool hasLocks(Session session, Statement cs)
        {

            if (cs == null)
            {
                return true;
            }

            _lock.EnterWriteLock();

            try
            {
                QNameManager.QName[] nameList = cs.getTableNamesForWrite();

                for (int i = 0; i < nameList.Length; i++)
                {
                    QNameManager.QName name = nameList[i];

                    if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                    {
                        continue;
                    }

                    Session holder = (Session)tableWriteLocks.get(name);

                    if (holder != null && holder != session)
                    {
                        return false;
                    }

                    Iterator it = tableReadLocks.get(name);

                    while (it.hasNext())
                    {
                        holder = (Session)it.next();

                        if (holder != session)
                        {
                            return false;
                        }
                    }
                }

                nameList = cs.getTableNamesForRead();

                for (int i = 0; i < nameList.Length; i++)
                {
                    QNameManager.QName name = nameList[i];

                    if (name.schema == SqlInvariants.SYSTEM_SCHEMA_QNAME)
                    {
                        continue;
                    }

                    Session holder = (Session)tableWriteLocks.get(name);

                    if (holder != null && holder != session)
                    {
                        return false;
                    }
                }

                return true;
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        // functional unit - list actions and translate id's

        /**
         * Return an array of all row actions sorted by System Change No.
         */
        public RowAction[] getRowActionList()
        {

            try
            {
                _lock.EnterWriteLock();

                Session[] sessions = database.sessionManager.getAllSessions();
                int[] tIndex = new int[sessions.Length];
                RowAction[] rowActions;
                int rowActionCount = 0;

                {
                    int actioncount = 0;

                    for (int i = 0; i < sessions.Length; i++)
                    {
                        actioncount += sessions[i].getTransactionSize();
                    }

                    rowActions = new RowAction[actioncount];
                }

                while (true)
                {
                    bool found = false;
                    long minChangeNo = long.MaxValue;
                    int sessionIndex = 0;

                    // find the lowest available SCN across all sessions
                    for (int i = 0; i < sessions.Length; i++)
                    {
                        int tSize = sessions[i].getTransactionSize();

                        if (tIndex[i] < tSize)
                        {
                            RowAction current =
                                (RowAction)sessions[i].rowActionList.get(
                                    tIndex[i]);

                            if (current.actionTimestamp < minChangeNo)
                            {
                                minChangeNo = current.actionTimestamp;
                                sessionIndex = i;
                            }

                            found = true;
                        }
                    }

                    if (!found)
                    {
                        break;
                    }

                    EfzArrayList currentList =
                        sessions[sessionIndex].rowActionList;

                    for (; tIndex[sessionIndex] < currentList.size(); )
                    {
                        RowAction current =
                            (RowAction)currentList.get(tIndex[sessionIndex]);

                        // if the next change no is in this session, continue adding
                        if (current.actionTimestamp == minChangeNo + 1)
                        {
                            minChangeNo++;
                        }

                        if (current.actionTimestamp == minChangeNo)
                        {
                            rowActions[rowActionCount++] = current;

                            tIndex[sessionIndex]++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                return rowActions;
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        /**
         * Return a lookup of all row ids for cached tables in transactions.
         */
        public DoubleIntIndex getTransactionIDList()
        {

            DoubleIntIndex lookup = new DoubleIntIndex(10, false);

            return lookup;
        }

        /**
         * Convert row ID's for cached table rows in transactions
         */
        public void convertTransactionIDs(DoubleIntIndex lookup) { }
    }
}
